package sky.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import sky.domain.City;
import sky.service.CityService;

import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 19.05.13
 * Time: 17:26
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class CityController {

    @Autowired
    private CityService cityService;

    @RequestMapping(value = "/city", method = RequestMethod.GET)
    public String cityInfo(@RequestParam("id") Integer id, Map<String, Object> map) {
        map.put("city", cityService.getCityById(id));
        return "city";
    }

    @RequestMapping(value = "/cities", method = RequestMethod.GET)
    public String cities(Map<String, Object> map) {
        map.put("cityList", cityService.listCity());
        map.put("NCity", new City());
        return "cities";
    }

    @RequestMapping(value = "/addCity", method = RequestMethod.POST)
    public String addCity(@ModelAttribute("city") City city, BindingResult result) {
        cityService.addCity(city);
        return "redirect:/cities";
    }

    @RequestMapping(value = "/cities/edit/{cityId}", method = RequestMethod.GET)
    public String editCity(@PathVariable("cityId") Integer cityId, Map<String, Object> map) {
        map.put("city", cityService.getCityById(cityId));
        return "editCity";
    }

    @RequestMapping(value = "/cities/edit/*", method = RequestMethod.POST)
    public String editCity(@ModelAttribute("city") City city, BindingResult result) {
        cityService.editCity(city);
        return "redirect:/cities";
    }

    @RequestMapping(value = "/cities/delete/{cityId}", method = RequestMethod.GET)
    public String deleteCity(@PathVariable("cityId") Integer cityId) {
        cityService.removeCity(cityId);
        return "redirect:/cities";
    }
}
